package com.ai.trickycards.ui.fragment

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.ai.trickycards.R
import com.ai.trickycards.databinding.AdapterBackgroundItemBinding
import com.ai.trickycards.databinding.AdapterPokerItemBinding
import com.ai.trickycards.databinding.FragmentCustomizeBinding
import com.ai.trickycards.entity.enumeration.PokerRankEnum
import com.ai.trickycards.entity.enumeration.PokerSuitEnum
import com.ai.trickycards.ui.adapter.BaseRecyclerAdapter
import com.ai.trickycards.ui.adapter.BaseViewHolder
import com.ai.trickycards.utils.onLifecycleState
import com.ai.trickycards.widgets.PokerCardView
import com.google.android.material.divider.MaterialDividerItemDecoration
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
import kotlin.time.Duration.Companion.seconds

@SuppressLint("NotifyDataSetChanged")
class CustomizeFragment : BaseFragment<FragmentCustomizeBinding>() {

    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?) = FragmentCustomizeBinding.inflate(inflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setRecyclerView(binding.recyclerBackground, BackgroundAdapter())
        setRecyclerView(binding.recyclerCardFace, CardFaceAdapter())
        setRecyclerView(binding.recyclerBackStyle, BackStyleAdapter())

        onLifecycleState {
            appViewModel.userInfoFlow.collect {
                println("duxl.log#CustomizeFragment#userInfoChange: $it")
                binding.recyclerBackground.adapter?.notifyDataSetChanged()
                binding.recyclerCardFace.adapter?.notifyDataSetChanged()
                binding.recyclerBackStyle.adapter?.notifyDataSetChanged()
            }
        }
    }

    private fun setRecyclerView(recycler: RecyclerView, adapter: BaseRecyclerAdapter) {
        val decoration = MaterialDividerItemDecoration(requireContext(), DividerItemDecoration.HORIZONTAL)
        decoration.dividerColor = Color.TRANSPARENT
        decoration.dividerThickness = (32 * displayMetrics.density).roundToInt()
        decoration.isLastItemDecorated = false
        recycler.addItemDecoration(decoration)
        recycler.adapter = adapter
    }

    private inner class BackgroundAdapter : BaseRecyclerAdapter(R.layout.adapter_background_item) {

        private val list = listOf(
            R.mipmap.background01,
            R.mipmap.background02,
            R.mipmap.background03,
            R.mipmap.background04,
            R.mipmap.background05
        )

        override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
            val binding = AdapterBackgroundItemBinding.bind(holder.itemView)
            binding.ivImg.setImageResource(list[position])

            val userInfo = appViewModel.userInfoFlow.value
            binding.ivImg.strokeWidth = if (userInfo.gameBg == list[position]) 2 * displayMetrics.density else 0f
            binding.tvDefault.isVisible = userInfo.gameBg == list[position]
            binding.root.isEnabled = userInfo.ownGameBgList.contains(list[position])
            if (binding.root.isEnabled) {
                binding.ivImg.imageTintMode = PorterDuff.Mode.SRC_ATOP
                binding.ivImg.imageTintList = ColorStateList.valueOf(Color.TRANSPARENT)
            } else {
                binding.ivImg.imageTintMode = PorterDuff.Mode.SRC_ATOP
                binding.ivImg.imageTintList = ColorStateList.valueOf(Color.parseColor("#B2000000"))
            }

            binding.root.setOnClickListener {
                if (userInfo.gameBg != list[position]) {
                    appViewModel.changeUserInfo(userInfo.copy(gameBg = list[position]))
                }
            }
        }

        override fun getItemCount() = list.size
    }

    private inner class CardFaceAdapter : BaseRecyclerAdapter(R.layout.adapter_poker_item) {

        private val list = listOf(
            Pair(PokerSuitEnum.Heart, PokerCardView.ShowType.Content01),
            Pair(PokerSuitEnum.Diamond, PokerCardView.ShowType.Content02),
            Pair(PokerSuitEnum.Club, PokerCardView.ShowType.Content03),
            Pair(PokerSuitEnum.Spade, PokerCardView.ShowType.Content04),
            Pair(PokerSuitEnum.Spade, PokerCardView.ShowType.Content05),
        )

        override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
            val binding = AdapterPokerItemBinding.bind(holder.itemView)
            binding.poker.suit = list[position].first
            binding.poker.rank = PokerRankEnum.RankA
            binding.poker.showType = list[position].second

            val userInfo = appViewModel.userInfoFlow.value
            binding.root.isEnabled = userInfo.ownCardFaceList.contains(list[position].second)
            binding.tvDefault.isVisible = userInfo.cardFace == list[position].second
            binding.vBorder.isVisible = userInfo.cardFace == list[position].second
            binding.poker.mask = !binding.root.isEnabled

            binding.root.setOnClickListener {
                if (userInfo.cardFace != list[position].second) {
                    appViewModel.changeUserInfo(userInfo.copy(cardFace = list[position].second))
                }
            }
        }

        override fun getItemCount() = list.size
    }

    private inner class BackStyleAdapter : BaseRecyclerAdapter(R.layout.adapter_poker_item) {

        private val list = listOf(
            PokerCardView.ShowType.Back01,
            PokerCardView.ShowType.Back02,
            PokerCardView.ShowType.Back03,
            PokerCardView.ShowType.Back04,
            PokerCardView.ShowType.Back05,
            PokerCardView.ShowType.Back06,
            PokerCardView.ShowType.Back07,
            PokerCardView.ShowType.Back08
        )

        override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
            val binding = AdapterPokerItemBinding.bind(holder.itemView)
            binding.poker.showType = list[position]

            val userInfo = appViewModel.userInfoFlow.value
            binding.root.isEnabled = userInfo.ownBackStyleList.contains(list[position])
            binding.tvDefault.isVisible = userInfo.backStyle == list[position]
            binding.vBorder.isVisible = userInfo.backStyle == list[position]
            binding.poker.mask = !binding.root.isEnabled

            binding.root.setOnClickListener {
                if (userInfo.backStyle != list[position]) {
                    appViewModel.changeUserInfo(userInfo.copy(backStyle = list[position]))
                }
            }
        }

        override fun getItemCount() = list.size
    }
}